<template>
	<view class="uni-forms">
		<slot></slot>
	</view>
</template>

<script>
	export default {
		name: "uni-forms",
		props: {
			model: {
				type: Object,
				default: () => ({})
			},
			rules: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				formItems: []
			};
		},
		methods: {
			// 添加表单项
			addItem(item) {
				this.formItems.push(item);
			},
			// 移除表单项
			removeItem(item) {
				const index = this.formItems.indexOf(item);
				if (index !== -1) {
					this.formItems.splice(index, 1);
				}
			},
			// 表单验证
			validate() {
				return new Promise((resolve, reject) => {
					let valid = true;
					let errors = [];

					this.formItems.forEach(item => {
						const fieldName = item.field;
						const fieldValue = this.model[fieldName];
						const fieldRules = this.rules[fieldName]?.rules || [];

						for (let rule of fieldRules) {
							if (rule.required && !fieldValue) {
								valid = false;
								errors.push({
									field: fieldName,
									message: rule.errorMessage
								});
								break;
							}
							if (rule.pattern && !rule.pattern.test(fieldValue)) {
								valid = false;
								errors.push({
									field: fieldName,
									message: rule.errorMessage
								});
								break;
							}
						}
					});

					if (valid) {
						resolve();
					} else {
						reject(errors);
					}
				});
			}
		}
	};
</script>

<style scoped>
	.uni-forms {
		width: 100%;
	}
</style>